import Vue from 'vue'
import VueRouter from 'vue-router'

// 1.创建路由组件
import Cookie from 'js-cookie'


Vue.use(VueRouter)

// 2.将路由与组件进行映射
const routes = [
    {
        path: '/',
        component: () => import('../views/Main.vue'),
        redirect: "/home",
        children: [
            {
                path: "/home",
                name: "home",
                component: () => import('../views/Home.vue'),
            },
            {
                path: "/demo",
                name: "demo",
                component: () => import('../views/demo.vue'),
            },
            {
                path: "/user",
                name: "user",
                component: () => import('../views/User'),
            },
            {
                path: "/mall",
                name: "mall",
                component: () => import('../views/Mall.vue'),
            },
            {
                path: "/page1",
                name: "page1",
                component: () => import('../views/PageOne'),
            },
            {
                path: "/page2",
                name: "page2",
                component: () => import('../views/PageTwo'),
            },
        ]
    },
    {
        path: "/login",
        name: 'login',
        component: () => import('../views/Login'),
    }

]

// 3.创建router实例
const router = new VueRouter({
    routes, // 缩写:相当于routes:routes
})

// 4.将router实例抛出
export default router

// 5.将router挂载到根节点上,根节点在main.js中

// 6.创建路由守卫
router.beforeEach((to, from, next) => {
    let token = Cookie.get('token');
    // 如果token不存在,且跳转的不是登录页面
    if (!token && to.name !== 'login') {
        next('/login');
    }
    // 若token存在则说明登录了,此时去的还是登录页面时，让其自动跳转至首页（此处不能进行重复登录）
    else if (token && to.name === 'login') {
        next('/home');
    } else {
        next();
    }
})

